package com.jerehedu.myapplication34.util;

import android.content.Context;

import com.jerehedu.myapplication34.entrty.Book;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 *  获取手机所有的后缀名为。txt的文件
 * Created by lenovo on 2016/11/4.
 */
public class GetAllBookFromPhone {
    public ArrayList<Book> mData=new ArrayList<>();
    SDOrLocalPath sdOrLocalPath=new SDOrLocalPath();
    public ArrayList<Book> findAllName(Context context){
        String a=sdOrLocalPath.getStoragePath(context,true);
        if(a!=null){
            File path = new File(a);
            File[] files = path.listFiles();// 读取
            getFileName(files);
        }
        String b=sdOrLocalPath.getStoragePath(context,false);
        if(b!=null){
            File path1 = new File(sdOrLocalPath.getStoragePath(context,false));
            File[] filess = path1.listFiles();// 读取
            getFileName(filess);
        }
        return mData;
    }

    private void getFileName(File[] files) {
        if (files != null) {// 先判断目录是否为空，否则会报空指针
            for (File file : files) {
                if (file.isDirectory()) {
                    getFileName(file.listFiles());
                } else {
                    String fileName = file.getName();
                    long blockSize=0;
                    try {
                        blockSize=getFileSize(file);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (fileName.endsWith(".txt")&&blockSize>1024*1024) {
                        Book book=new Book();
                        book.setIsLocal(1);
                        book.setName(fileName.substring(0,fileName.length()-4));
                        book.setUrl(file.getAbsolutePath());
                        double a=((double)blockSize)/1024/1024;
                        DecimalFormat df = new DecimalFormat( "#.00 ");
                        String ss=df.format(a);
                        book.setSize(Double.parseDouble(ss));
                        mData.add(book);
                    }
                }
            }
        }
    }

    private static long getFileSize(File file) throws Exception
    {
        long size = 0;
        if (file.exists()){
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
            if(fis!=null){
                fis.close();
            }
        }
        else{
            file.createNewFile();
        }

        return size;
    }
}
